"""
中央温控系统主程序 - 现代化版本
"""
import tkinter as tk
from tkinter import messagebox, simpledialog
import sys
from core.central_ac import CentralAC
from ui.client import ClientPanel
from ui.monitor import MonitorPanel
from ui.reception import ReceptionPanel
from ui.styles import COLORS, FONTS, SPACING, create_card_frame, create_modern_button
from core import config


class MainApplication:
    """主应用程序"""
    
    def __init__(self):
        # 初始化中央空调系统
        self.central_ac = CentralAC(
            total_rooms=config.TOTAL_ROOMS,
            max_service_objects=config.MAX_SERVICE_OBJECTS
        )
        
        # 启动中央空调
        self.central_ac.start()
        
        # 创建主窗口
        self.root = tk.Tk()
        self.root.title("中央温控系统")
        self.root.geometry("750x700")
        self.root.resizable(True, True)  # 允许调整大小
        self.root.minsize(750, 700)  # 设置最小尺寸
        self.root.configure(bg=COLORS['background'])
        
        # 添加全屏支持（F11切换）
        self.is_fullscreen = False
        self.root.bind('<F11>', self._toggle_fullscreen)
        self.root.bind('<Escape>', self._exit_fullscreen)
        
        self._setup_ui()
        
        # 窗口关闭事件
        self.root.protocol("WM_DELETE_WINDOW", self._on_closing)
    
    def _setup_ui(self):
        """设置UI界面"""
        # 标题栏
        header_frame = tk.Frame(
            self.root,
            bg=COLORS['primary'],
            height=120
        )
        header_frame.pack(fill=tk.X)
        header_frame.pack_propagate(False)
        
        # 主标题
        title_label = tk.Label(
            header_frame,
            text="中央温控系统",
            font=('Segoe UI', 32, 'bold'),
            bg=COLORS['primary'],
            fg='white'
        )
        title_label.pack(pady=(SPACING['xl'], SPACING['xs']))
        
        # 副标题
        subtitle_label = tk.Label(
            header_frame,
            text="智能管理 · 节能环保 · 高效服务",
            font=FONTS['body'],
            bg=COLORS['primary'],
            fg='#E0E7FF'
        )
        subtitle_label.pack()
        
        # 主内容区
        content_frame = tk.Frame(
            self.root,
            bg=COLORS['background'],
            padx=SPACING['xl'],
            pady=SPACING['xl']
        )
        content_frame.pack(fill=tk.BOTH, expand=True)
        
        # 系统信息卡片
        self._create_info_section(content_frame)
        
        # 功能按钮区
        self._create_action_section(content_frame)
    
    def _create_info_section(self, parent):
        """创建系统信息区域"""
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.X, pady=(0, SPACING['lg']))
        card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 标题
        tk.Label(
            card,
            text="系统配置",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 配置信息网格
        info_grid = tk.Frame(card, bg=COLORS['card_bg'])
        info_grid.pack(fill=tk.X)
        
        # 配置项列表
        config_items = [
            ("总房间数", f"{config.TOTAL_ROOMS} 间"),
            ("最大服务数", f"{config.MAX_SERVICE_OBJECTS} 个"),
            ("时间片", f"{config.WAITING_TIME_SLICE} 秒"),
            ("制冷范围", f"{config.TEMP_RANGE_COOLING[0]}-{config.TEMP_RANGE_COOLING[1]}°C"),
            ("制热范围", f"{config.TEMP_RANGE_HEATING[0]}-{config.TEMP_RANGE_HEATING[1]}°C"),
            ("计费标准", f"{config.COST_PER_UNIT} 元/度"),
        ]
        
        # 创建两列布局
        for i, (label, value) in enumerate(config_items):
            row = i // 2
            col = i % 2
            
            item_frame = tk.Frame(info_grid, bg=COLORS['card_bg'])
            item_frame.grid(row=row, column=col, sticky=tk.W, padx=(0, SPACING['xl']), pady=SPACING['sm'])
            
            tk.Label(
                item_frame,
                text=label,
                font=FONTS['body'],
                fg=COLORS['text_secondary'],
                bg=COLORS['card_bg']
            ).pack(side=tk.LEFT, padx=(0, SPACING['sm']))
            
            tk.Label(
                item_frame,
                text=value,
                font=FONTS['body_bold'],
                fg=COLORS['primary'],
                bg=COLORS['card_bg']
            ).pack(side=tk.LEFT)
    
    def _create_action_section(self, parent):
        """创建功能按钮区域"""
        shadow_frame, card = create_card_frame(parent)
        shadow_frame.pack(fill=tk.BOTH, expand=True)
        card.config(padx=SPACING['lg'], pady=SPACING['lg'])
        
        # 标题
        tk.Label(
            card,
            text="系统功能",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['card_bg']
        ).pack(anchor=tk.W, pady=(0, SPACING['md']))
        
        # 按钮容器
        buttons_frame = tk.Frame(card, bg=COLORS['card_bg'])
        buttons_frame.pack(fill=tk.BOTH, expand=True)
        
        # 功能按钮列表
        buttons_config = [
            {
                'text': '客户端控制面板',
                'desc': '房间空调控制和设置',
                'command': self._open_client_panel,
                'style': 'primary'
            },
            {
                'text': '管理员监控系统',
                'desc': '实时监控和服务管理',
                'command': self._open_monitor_panel,
                'style': 'info'
            },
            {
                'text': '前台系统',
                'desc': '账单查询和统计报表',
                'command': self._open_reception_panel,
                'style': 'success'
            },
        ]
        
        for btn_config in buttons_config:
            # 按钮容器（增加高度以完整显示描述）
            btn_container = tk.Frame(
                buttons_frame,
                bg=COLORS['border'],
                height=85
            )
            btn_container.pack(fill=tk.X, pady=(0, SPACING['md']))
            btn_container.pack_propagate(False)
            
            # 内部按钮框
            btn_inner = tk.Frame(btn_container, bg=COLORS['surface'])
            btn_inner.pack(fill=tk.BOTH, expand=True, padx=1, pady=1)
            
            # 创建可点击的区域
            btn_frame = tk.Frame(btn_inner, bg=COLORS['surface'], cursor='hand2')
            btn_frame.pack(fill=tk.BOTH, expand=True, padx=SPACING['lg'], pady=SPACING['md'])
            
            # 按钮文本
            text_label = tk.Label(
                btn_frame,
                text=btn_config['text'],
                font=FONTS['subheading'],
                fg=COLORS['text_primary'],
                bg=COLORS['surface'],
                cursor='hand2',
                anchor=tk.W
            )
            text_label.pack(anchor=tk.W, fill=tk.X)
            
            # 描述文本
            desc_label = tk.Label(
                btn_frame,
                text=btn_config['desc'],
                font=FONTS['small'],
                fg=COLORS['text_secondary'],
                bg=COLORS['surface'],
                cursor='hand2',
                anchor=tk.W
            )
            desc_label.pack(anchor=tk.W, fill=tk.X, pady=(SPACING['xs'], 0))
            
            # 绑定点击事件
            for widget in [btn_frame, text_label, desc_label]:
                widget.bind('<Button-1>', lambda e, cmd=btn_config['command']: cmd())
                widget.bind('<Enter>', lambda e, f=btn_inner: f.config(bg='#F3F4F6'))
                widget.bind('<Leave>', lambda e, f=btn_inner: f.config(bg=COLORS['surface']))
            
            # 让子控件也响应悬停
            for widget in [text_label, desc_label]:
                widget.bind('<Enter>', lambda e, f=btn_inner, t=text_label, d=desc_label: [
                    f.config(bg='#F3F4F6'),
                    t.config(bg='#F3F4F6'),
                    d.config(bg='#F3F4F6')
                ])
                widget.bind('<Leave>', lambda e, f=btn_inner, t=text_label, d=desc_label: [
                    f.config(bg=COLORS['surface']),
                    t.config(bg=COLORS['surface']),
                    d.config(bg=COLORS['surface'])
                ])
        
        # 退出按钮
        exit_button = create_modern_button(
            buttons_frame,
            "退出系统",
            self._on_closing,
            style='danger',
            height=2
        )
        exit_button.pack(fill=tk.X, pady=(SPACING['md'], 0))
    
    def _open_client_panel(self):
        """打开客户端控制面板"""
        # 创建自定义对话框
        dialog = tk.Toplevel(self.root)
        dialog.title("选择房间")
        dialog.geometry("400x200")
        dialog.configure(bg=COLORS['background'])
        dialog.transient(self.root)
        dialog.grab_set()
        
        # 居中显示
        dialog.update_idletasks()
        x = (dialog.winfo_screenwidth() // 2) - (400 // 2)
        y = (dialog.winfo_screenheight() // 2) - (200 // 2)
        dialog.geometry(f"400x200+{x}+{y}")
        
        # 内容
        content = tk.Frame(dialog, bg=COLORS['background'], padx=SPACING['xl'], pady=SPACING['xl'])
        content.pack(fill=tk.BOTH, expand=True)
        
        tk.Label(
            content,
            text="请输入房间号",
            font=FONTS['heading'],
            fg=COLORS['text_primary'],
            bg=COLORS['background']
        ).pack(pady=(0, SPACING['lg']))
        
        tk.Label(
            content,
            text=f"(1-{config.TOTAL_ROOMS})",
            font=FONTS['body'],
            fg=COLORS['text_secondary'],
            bg=COLORS['background']
        ).pack(pady=(0, SPACING['md']))
        
        # 输入框
        entry_var = tk.StringVar()
        entry_container = tk.Frame(content, bg=COLORS['border'])
        entry_container.pack(pady=(0, SPACING['lg']))
        
        entry = tk.Entry(
            entry_container,
            textvariable=entry_var,
            font=FONTS['heading'],
            width=15,
            relief=tk.FLAT,
            bg=COLORS['surface'],
            fg=COLORS['text_primary'],
            justify=tk.CENTER
        )
        entry.pack(padx=2, pady=2)
        entry.focus()
        
        # 按钮
        def on_ok():
            room_id = entry_var.get().strip()
            if room_id:
                # 补充前导零
                if room_id.isdigit():
                    room_id = f"{int(room_id):03d}"
                
                # 验证房间号
                if room_id in self.central_ac.room_states:
                    dialog.destroy()
                    ClientPanel(room_id, self.central_ac)
                else:
                    messagebox.showerror("✗ 错误", f"房间号 {room_id} 不存在", parent=dialog)
        
        def on_cancel():
            dialog.destroy()
        
        # 绑定回车键
        entry.bind('<Return>', lambda e: on_ok())
        entry.bind('<Escape>', lambda e: on_cancel())
        
        btn_frame = tk.Frame(content, bg=COLORS['background'])
        btn_frame.pack()
        
        ok_btn = create_modern_button(btn_frame, "✓ 确定", on_ok, style='primary')
        ok_btn.pack(side=tk.LEFT, padx=(0, SPACING['sm']))
        
        cancel_btn = create_modern_button(btn_frame, "✕ 取消", on_cancel, style='danger')
        cancel_btn.pack(side=tk.LEFT)
    
    def _open_monitor_panel(self):
        """打开管理员监控面板"""
        MonitorPanel(self.central_ac)
    
    def _open_reception_panel(self):
        """打开前台系统面板"""
        ReceptionPanel(self.central_ac)
    
    def _toggle_fullscreen(self, event=None):
        """切换全屏模式"""
        self.is_fullscreen = not self.is_fullscreen
        self.root.attributes('-fullscreen', self.is_fullscreen)
    
    def _exit_fullscreen(self, event=None):
        """退出全屏"""
        self.is_fullscreen = False
        self.root.attributes('-fullscreen', False)
    
    def _on_closing(self):
        """关闭程序"""
        if messagebox.askokcancel("退出确认", "确定要退出系统吗？\n这将关闭所有窗口。"):
            self.central_ac.stop()
            self.root.destroy()
            sys.exit(0)
    
    def run(self):
        """运行应用程序"""
        self.root.mainloop()


def main():
    """主函数"""
    print("=" * 60)
    print("中央温控系统".center(56))
    print("=" * 60)
    print("系统正在启动...")
    
    try:
        app = MainApplication()
        print("系统启动成功!")
        print("-" * 60)
        app.run()
    except KeyboardInterrupt:
        print("\n系统被用户中断")
    except Exception as e:
        print(f"系统启动失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        print("系统已关闭")


if __name__ == "__main__":
    main()
